<!--店铺管理-->
<script setup lang="ts">
  import axios, {AxiosPromise} from "axios";
  import lodash from 'lodash-es'

  defineOptions({
    name: "Subjects",
    inheritAttrs: false,
  });

  import {
    getSubjectsPage,
    getSubjectsForm,
    saveSubjects,
    deleteSubjects,
    exportSubject,
    importSubject
  } from "@/api/subjects";
  import {getCompanyList} from "@/api/company";
  import {findAll} from "@/api/accessory";

  import { SubjectsQuery, SubjectsForm } from "@/api/subjects/types";
  import {CompanyForm} from "@/api/company/types";
  import {AccessoryList} from "@/api/accessory/types";
  import {ElLoading, UploadFile} from "element-plus";
  import {antiAudit} from "@/api/fileAudit";

  const queryFormRef = ref(ElForm);
  const dataFormRef = ref(ElForm);

  const loading = ref(false);
  const ids = ref<number[]>([]);
  const total = ref(0);
  const companyList = ref<CompanyForm[]>();

  const queryParams = reactive<SubjectsQuery>({
    pageNum: 1,
    pageSize: 20,
  });

  const subjectsList = ref<[]>();
  const accessoryList = reactive<AccessoryList>({
    value: []
  });

  const dialog = reactive<DialogOption>({
    visible: false,
  });

  const formData = reactive<SubjectsForm>({});

  const rules = reactive({
    companyCode: [{ required: true, message: "请选择入账主体", trigger: "blur" }],
    firstCode: [{ required: true, message: "请输入一级科目编码", trigger: "blur" }],
    firstName: [{ required: true, message: "请输入一级科目名称", trigger: "blur" }],
    lastCode: [{ required: true, message: "请输入末级科目编码", trigger: "blur" }],
    lastName: [{ required: true, message: "请输入末级科目名称", trigger: "blur" }],
    accountingProject: [{ required: true, message: "请输入记账项目分类", trigger: "blur" }],
    borrowing: [{ required: true, message: "请选择借贷方向", trigger: "blur" }],
  });

  const importDialog = reactive<DialogOption>({
    title: "科目导入",
    visible: false,
  });

  const excelFile = ref<File>();
  const excelFilelist = ref<File[]>([]);

  const importMsg = ref([])
  const resultDialog = reactive<DialogOption>({
    title: "导入错误信息",
    visible: false,
  });

  /**
   * 查询
   */
  function handleQuery() {
    loading.value = true;
    getSubjectsPage(queryParams)
            .then(({ data }) => {
              subjectsList.value = data.list;
              total.value = data.total;
            })
            .finally(() => {
              loading.value = false;
            });
  }

  /**
   * 重置查询
   */
  function resetQuery() {
    queryFormRef.value.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /**
   * 行checkbox change事件
   */
  function handleSelectionChange(selection: any) {
    ids.value = selection.map((item: any) => item.id);
  }

  /**
   * 字典类型表单提交
   */
  function handleSubmit() {
    dataFormRef.value.validate((isValid: boolean) => {
      if (isValid) {
        loading.value = false;
        formData.accessoryNames = lodash.join(formData.accessoryList, ',')
        saveSubjects(formData)
                .then(() => {
                  ElMessage.success("保存成功");
                  closeDialog();
                  handleQuery();
                })
                .finally(() => (loading.value = false));
      }
    });
  }

  /**
   * 打开字典类型表单弹窗
   *
   * @param dicTypeId 字典类型ID
   */
  async function openDialog(id?: number) {
    await getAllCompanyList()
    await getAccessoryList()
    dialog.visible = true;
    if (id) {
      dialog.title = "修改科目";
      getSubjectsForm(id).then(({ data }) => {
        Object.assign(formData, data);
        if (formData.accessoryNames !== undefined && formData.accessoryNames !== null && formData.accessoryNames !== '') {
          formData.accessoryList = formData.accessoryNames.split(',')
        }
      });
    } else {
      dialog.title = "新增科目";
    }
  }

  /**
   * 关闭弹窗
   */
  function closeDialog() {
    dialog.visible = false;
    resetForm();
  }

  /**
   * 重置表单
   */
  function resetForm() {
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();

    formData.id = undefined;
    formData.accessoryList = []
    accessoryList.value = []
  }

  /**
   * 删除事件
   */
  function handleDelete(dictTypeId?: number) {
    const dictTypeIds = [dictTypeId || ids.value].join(",");
    if (!dictTypeIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      deleteSubjects(dictTypeIds).then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    });
  }

  const dictDataDialog = reactive<DialogOption>({
    visible: false,
  });

  /**
   * 获取入账主体列表
   *
   */
  async function getAllCompanyList() {
    getCompanyList().then((response) => {
      companyList.value = response.data;
    });
  }

  /**
   * 获取辅助项列表
   */
  async function getAccessoryList(){
    findAll().then((response) => {
      if (response.data !== undefined && response.data !== null && response.data.length > 0) {
        const head = lodash.head(response.data)
        for (let key of Object.keys(head)) {
          const headValue = lodash.get(head, key)
          if (key.includes('Name') && headValue !== null && headValue !== '') {
            accessoryList.value.push(headValue)
          }
        }
      }
    });
  }

  /** 导出科目 */
  function handleSubjectExport() {
    exportSubject().then((response: any) => {
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
      });
      const a = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 下载的链接
      a.href = href;
      a.download = decodeURI(
              response.headers["content-disposition"].split(";")[1].split("=")[1]
      ); // 获取后台设置的文件名称
      document.body.appendChild(a);
      a.click(); // 点击导出
      document.body.removeChild(a); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    });
  }

  /** 打开导入弹窗 */
  async function openImportDialog() {
    importDialog.visible = true;
  }

  /**
   * Excel文件change事件
   *
   * @param file
   */
  function handleExcelChange(file: UploadFile) {
	  if (file.size !== undefined) {
		  if (file.size > 20*1024*1024) {
			  ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			  return false
		  }
	  }
    if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
      ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
      excelFile.value = undefined;
      excelFilelist.value = [];
      return false;
    }
    excelFile.value = file.raw;
  }

  /** 导入科目提交 */
  function handleSubjectImport() {
    if (!excelFile.value) {
      ElMessage.warning("上传Excel文件不能为空");
      return false;
    }
    const importLoading = ElLoading.service({
      lock: true,
      text: '导入中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    importSubject(excelFile.value).then((response) => {
      importLoading.close()
      closeImportDialog();
      if (response.data.length > 0) {
        importMsg.value = response.data
        resultDialog.visible = true
      }else{
        ElMessage.success('导入成功');
        resetQuery();
      }
    });
  }

  /**  关闭导入弹窗 */
  function closeImportResultDialog() {
    resultDialog.visible = false;
  }

  /**  关闭导入弹窗 */
  function closeImportDialog() {
    importDialog.visible = false;
    excelFile.value = undefined;
    excelFilelist.value = [];
  }

  onMounted(() => {
    handleQuery();
  });
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键词" prop="keywords">
          <el-input
                  v-model="queryParams.keywords"
                  placeholder=""
                  clearable
                  @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
          ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
                    v-hasPerm="['sys:subjects:save']"
                    type="success"
                    @click="openDialog()"
            ><i-ep-plus />新增</el-button
            >
            <el-button
                    type="danger"
										v-hasPerm="['sys:subjects:delete']"
                    :disabled="ids.length === 0"
                    @click="handleDelete()"
            ><i-ep-delete />删除</el-button
            >
          </div>
          <div>
            <el-button class="ml-3" @click="openImportDialog"
            ><template #icon><i-ep-top /></template>导入</el-button
            >
            <el-button class="ml-3" @click="handleSubjectExport"
            ><template #icon><i-ep-download /></template>下载模板</el-button
            >
          </div>
        </div>
          </template>
      <el-table
              size="small"
              :height="subjectsList && subjectsList.length > 0 ? 580 : 100"
              :header-row-style="{color: 'dimgray'}"
              v-loading="loading"
              highlight-current-row
              :data="subjectsList"
              border
              @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column show-overflow-tooltip label="入账主体" prop="companyName"/>
        <el-table-column show-overflow-tooltip label="一级科目编码" prop="firstCode"/>
        <el-table-column show-overflow-tooltip label="一级科目名称" prop="firstName"/>
        <el-table-column show-overflow-tooltip label="末级科目编码" prop="lastCode"/>
        <el-table-column show-overflow-tooltip label="末级科目名称" prop="lastName"/>
        <el-table-column show-overflow-tooltip label="记账项目分类" prop="accountingProject"/>
        <el-table-column show-overflow-tooltip label="辅助项" prop="accessoryNames"/>
        <el-table-column show-overflow-tooltip label="借贷方向" prop="borrowing"/>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
                    v-hasPerm="['sys:subjects:save']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="openDialog(scope.row.id)"
            ><i-ep-edit />编辑</el-button
            >
            <el-button
                    v-hasPerm="['sys:subjects:delete']"
                    type="primary"
                    link
                    size="small"
                    @click.stop="handleDelete(scope.row.id)"
            ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
              v-if="total > 0"
              v-model:total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
            v-model="dialog.visible"
            :title="dialog.title"
            width="500px"
            :close-on-click-modal="false"
            @close="closeDialog"
    >
      <el-form
              ref="dataFormRef"
              :model="formData"
              :rules="rules"
              label-width="120px"
      >
        <el-form-item label="入账主体" prop="companyCode">
          <el-select class="yz-el-select" v-model="formData.companyCode" placeholder="请选择">
            <el-option
                    v-for="item in companyList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="一级科目编码" prop="firstCode">
          <el-input v-model="formData.firstCode" placeholder="请输入一级科目编码" clearable/>
        </el-form-item>
        <el-form-item label="一级科目名称" prop="firstName">
          <el-input v-model="formData.firstName" placeholder="请输入一级科目名称" clearable/>
        </el-form-item>
        <el-form-item label="末级科目编码" prop="lastCode">
          <el-input v-model="formData.lastCode" placeholder="请输入末级科目编码" clearable/>
        </el-form-item>
        <el-form-item label="末级科目名称" prop="lastName">
          <el-input v-model="formData.lastName" placeholder="请输入末级科目名称" clearable/>
        </el-form-item>
        <el-form-item label="记账项目分类" prop="accountingProject">
          <dictionary v-model="formData.accountingProject" type-code="jzxmmc" clearable/>
        </el-form-item>
        <el-form-item label="辅助项" prop="accessory">
          <el-select class="yz-el-select" v-model="formData.accessoryList" multiple placeholder="请选择辅助项">
            <el-option
                    v-for="item in accessoryList.value"
                    :key="item"
                    :label="item"
                    :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="借贷方向" prop="borrowing">
          <el-radio-group v-model="formData.borrowing" class="ml-4">
            <el-radio label="借" size="large">借</el-radio>
            <el-radio label="贷" size="large">贷</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog
            v-model="importDialog.visible"
            :title="importDialog.title"
            width="600px"
            append-to-body
            @close="closeImportDialog"
    >
      <el-form label-width="80px">

        <el-form-item label="Excel">
          <el-upload
                  class="upload-demo"
                  action=""
                  drag
                  :auto-upload="false"
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                  :file-list="excelFilelist"
                  :on-change="handleExcelChange"
                  :limit="1"
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled/>
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubjectImport">确 定</el-button>
          <el-button @click="closeImportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
            v-model="resultDialog.visible"
            :title="resultDialog.title"
            width="600px"
            append-to-body
            :close-on-click-modal="false"
            @close="closeImportResultDialog"
    >
      <span v-for="msg in importMsg">{{msg}}<br></span>
    </el-dialog>
  </div>
</template>
